//单个导出的导入语法
import {
  registApi,
  loginApi,
  loadApi
} from '../../api/customerApi.js'

import {
  setToken
} from '../../utils/local.js'

//默认导出的导入语法
import router from '../../router/index.js'

export default {
  namespaced: true,
  state: {
    user_phone: '',
    user_password: '',
    confirm_password: '',
    user_name: '',
    user_info: null
  },
  getters: {},
  mutations: {
    set_user_info(state, value) {
      state.user_info = value;
    }
  },
  actions: {
    //注册
    customer_regist(context) {
      //调用customerApi.js中方法
      registApi({
        user_phone: context.state.user_phone,
        user_password: context.state.user_password,
        user_name: context.state.user_name,
      }).then(function(response) {
        //注册成功
        if (response.data.httpcode == 200) {
          //自动登录
          context.dispatch('customer_login')
        }
      })
    },
    customer_login(context) {
      loginApi({
        username: context.state.user_phone,
        password: context.state.user_password
      }).then(response => {
        //登录成功
        if (response.data.httpcode == 200) {
          //保存token
          setToken(response.data.data);
          //获取用户信息
          context.dispatch('customer_load')
          //跳转首页
          router.push({
            path: '/'
          });
        }
      })
    },
    //获取用户信息
    customer_load(context) {
      loadApi({}).then(function(response) {
        if (response.data.httpcode == 200) {
          context.commit('set_user_info', response.data.data)
        }
      })
    }
  },
}
